/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ruoyi.common.utils.jxls;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import static java.util.Objects.nonNull;
import static org.apache.commons.lang3.StringUtils.isNotBlank;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DelSheet {

    private static final Logger LOG = LoggerFactory.getLogger(DelSheet.class);

    /**
     * 删除指定的Sheet
     *
     * @param targetFile 目标文件
     * @param sheetName Sheet名称
     */
    public static void deleteSheet(String targetFile, String sheetName) {
        if (isNotBlank(targetFile) && isNotBlank(sheetName)) {
            try (FileInputStream fis = new FileInputStream(targetFile)) {
                HSSFWorkbook wb = new HSSFWorkbook(fis);
                fileWrite(targetFile, wb);
                //删除Sheet 
                wb.removeSheetAt(wb.getSheetIndex(sheetName));
                fileWrite(targetFile, wb);
            } catch (Exception e) {
                e.printStackTrace();
                LOG.error("failed to delete sheet:{}", e.getMessage());
            }
        } else {
            LOG.error("failed to delete sheet:{}, {}", targetFile, sheetName);
        }
    }

    /**
     * 写隐藏/删除后的Excel文件
     *
     * @param targetFile 目标文件
     * @param wb Excel对象
     * @throws Exception
     */
    public static void fileWrite(String targetFile, HSSFWorkbook wb) throws Exception {
        if (isNotBlank(targetFile) && nonNull(wb)) {
            try (FileOutputStream fileOut = new FileOutputStream(targetFile)) {
                wb.write(fileOut);
            } catch (Exception e) {
                e.printStackTrace();
                LOG.error("failed to write file:{}", e.getMessage());
            }
        } else {
            LOG.error("failed to write file:{}", targetFile);
        }
    }

}
